<?php

namespace App\Console\Commands\CallingCards\AdvClueCallback;

use App\Remote\OceanEngine\Clue;
use App\Remote\XiaoKe\CustomerRemote;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;

class CallbackToDyCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'AdvClueCallback:toDy {executeDate?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '广告有效线索回传 - 抖音';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     * @throws ValidationException
     */
    public function handle(): int
    {
        $executeDate = $this->input->getArgument("executeDate");

        if ($executeDate) {
            $baseDt = Carbon::createFromDate($executeDate);

            $startTimestamp    = $baseDt->startOfDay()->timestamp;
            $todayEndTimestamp = $baseDt->clone()->endOfDay()->timestamp;

            $hoursIndex = 1;
            $sum        = 0;
            while ($startTimestamp < $todayEndTimestamp) {
                $startDatetime = Carbon::createFromTimestamp($startTimestamp)->format("Y-m-d H:i:s");
                $endTimestamp  = $startTimestamp + (60 * 60) - 1;
                $endDatetime   = Carbon::createFromTimestamp($endTimestamp)->format("Y-m-d H:i:s");

                $pageNum      = 1;
                $customerList = CustomerRemote::list($startDatetime, $endDatetime, $pageNum);
                $sum          = $sum + count($customerList["dataList"] ?? []);

                collect($customerList["dataList"] ?? [])->each(function ($customer) {
                    $customerDetail = CustomerRemote::detail($customer["id"]);
                    $mobile         = self::getCustomerField($customerDetail["customerInfoList"], "s_mobile_phone");
                    $clueId         = self::getCustomerField($customerDetail["customerInfoList"], "c_xiansuoid1");
                    $advId          = self::getCustomerField($customerDetail["customerInfoList"], "c_guanggaozhuid");
                    $advName        = self::getCustomerField($customerDetail["customerInfoList"],
                        "c_guanggaozhumingcheng");

                    if (!str_contains($clueId, "-")) {
                        $this->info($customer["id"] . "===" . $mobile . "====" . $clueId . "===" . $advId . "===" . $advName);
                        Clue::callback($clueId, $advId);
                    }
                });

                $startTimestamp = $endTimestamp + 1;
                $this->info($this->description . $hoursIndex . ". from " . $startDatetime . " to " . $endDatetime);
                $hoursIndex++;
            }
        } else {
            $baseDt        = Carbon::now();
            $startDatetime = $baseDt->clone()->subMinutes(20)->format("Y-m-d H:i:s");
            $endDatetime   = $baseDt->clone()->format("Y-m-d H:i:s");

            $customerList = CustomerRemote::list(
                $startDatetime,
                $endDatetime
            );

            collect($customerList["dataList"] ?? [])->each(function ($customer) {
                $customerDetail = CustomerRemote::detail($customer["id"]);
                $mobile         = self::getCustomerField($customerDetail["customerInfoList"], "s_mobile_phone");
                $clueId         = self::getCustomerField($customerDetail["customerInfoList"], "c_xiansuoid1");
                $advId          = self::getCustomerField($customerDetail["customerInfoList"], "c_guanggaozhuid");
                $advName        = self::getCustomerField($customerDetail["customerInfoList"], "c_guanggaozhumingcheng");

                if (!str_contains($clueId, "-")) {
                    $this->info($customer["id"] . "===" . $mobile . "====" . $clueId . "===" . $advId . "===" . $advName);
                    Clue::callback($clueId, $advId);
                }
            });

            $this->info($this->description . ". from " . $startDatetime . " to " . $endDatetime);
        }

        return 0;
    }

    /**
     * 获取自定义字段信息
     *
     * @param array $customerList
     * @param string $customerField
     * @return mixed
     */
    public static function getCustomerField(array $customerList, string $customerField)
    {
        $fieldGroup = collect($customerList)->where("apiName", "$customerField")->first();
        return attributeGet($fieldGroup, "value.0", "");
    }
}
